package cn.com.blueInfo.bpm.system.repository.impl;

import cn.com.blueInfo.bpm.common.entity.BaseEntity;
import cn.com.blueInfo.bpm.common.enums.BaseDeleted;
import cn.com.blueInfo.bpm.common.repository.BaseRepository;
import cn.com.blueInfo.bpm.system.entity.UserRole;
import cn.com.blueInfo.bpm.system.mapper.UserRoleMapper;
import cn.com.blueInfo.bpm.system.repository.UserRoleRepository;
import cn.com.blueInfo.bpm.system.request.UserRoleDTO;
import cn.com.blueInfo.core.entity.CurrentLoginUserInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户-角色关联表 数据服务实现类
 * @author suxch
 * @since 2025-09-01 19:17:41
 */
@Log4j2
@Service
public class UserRoleRepositoryImpl
        extends ServiceImpl<UserRoleMapper, UserRole>
        implements UserRoleRepository, BaseRepository<UserRole, UserRoleDTO.QueryDTO> {

    @Autowired
    private CurrentLoginUserInfo currentLoginUserInfo;

    /**
     * 提供获取 CurrentLoginUserInfo 的方法（由实现类提供，避免接口中注入）
     * @return CurrentLoginUserInfo
     */
    @Override
    public CurrentLoginUserInfo getCurrentLoginUserInfo() {
        return currentLoginUserInfo;
    }

    /**
     * 新增用户-角色关联
     * @param userRole 用户-角色关联参数
     */
    @Override
    public Integer createUserRole(UserRole userRole) {
        return sqlExecuteResult(save(userRole));
    }

    /**
     * 批量新增用户-角色关联
     * @param userRoleList 用户-角色关联参数列表
     */
    @Override
    public Integer batchCreateUserRole(List<UserRole> userRoleList) {
        return sqlExecuteResult(saveBatch(userRoleList), userRoleList.size());
    }

    /**
     * 删除用户-角色关联
     * @param userRoleId 用户-角色关联ID
     */
    @Override
    public Integer deleteUserRole(Long userRoleId) {
        UserRole userRole = new UserRole();
        userRole.setId(userRoleId);
        userRole.setDeleted(BaseDeleted.DELETED);
        return sqlExecuteResult(removeById(userRole));
    }

    /**
     * 批量删除用户-角色关联
     * @param userRoleIdList 用户-角色关联ID列表
     */
    @Override
    public Integer batchDeleteUserRole(List<Long> userRoleIdList) {
        List<UserRole> userRoleList = new ArrayList<>();
        for (Long userRoleId : userRoleIdList) {
            UserRole userRole = new UserRole();
            userRole.setId(userRoleId);
            userRole.setDeleted(BaseDeleted.DELETED);
            userRoleList.add(userRole);
        }
        return sqlExecuteResult(removeBatchByIds(userRoleList), userRoleList.size());
    }

    /**
     * 更新部分用户-角色关联
     * @param userRole 用户-角色关联参数
     */
    @Override
    public Integer updateUserRolePartial(UserRole userRole) {
        validateUpdateId(userRole.getId());
        LambdaUpdateWrapper<UserRole> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserRole::getId, userRole.getId());
        return sqlExecuteResult(update(updateWrapper));
    }

    /**
     * 更新全部用户-角色关联
     * @param userRole 用户-角色关联参数
     */
    @Override
    public Integer updateUserRole(UserRole userRole) {
        validateUpdateId(userRole.getId());
        return sqlExecuteResult(updateById(userRole));
    }

    /**
     * 查询一条用户-角色关联
     * @param userRoleId 用户-角色关联ID
     */
    @Override
    public UserRole getUserRoleById(Long userRoleId) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getId, userRoleId);
        return getOne(queryWrapper);
    }

    /**
     * 分页查询用户-角色关联
     * @param userRoleQueryDTO 用户-角色关联参数
     */
    @Override
    public Page<UserRole> getUserRolePage(UserRoleDTO.QueryDTO userRoleQueryDTO) {
        Page<UserRole> userRolePage = new Page<>(
                userRoleQueryDTO.getPage(), userRoleQueryDTO.getSize());
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, userRoleQueryDTO);

        BaseDeleted deleted = userRoleQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeletePage(userRolePage, queryWrapper);
        } else {
            return page(userRolePage, queryWrapper);
        }
    }

    /**
     * 根据条件查询 用户-角色关联 数量
     * @param userRoleQueryDTO 用户-角色关联参数
     */
    @Override
    public Long getUserRoleCount(UserRoleDTO.QueryDTO userRoleQueryDTO) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, userRoleQueryDTO);

        BaseDeleted deleted = userRoleQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeleteCount(queryWrapper);
        } else {
            return count(queryWrapper);
        }
    }

    /**
     * 根据条件查询 用户-角色关联
     * @param userRoleQueryDTO 用户-角色关联参数
     */
    @Override
    public List<UserRole> getUserRoleList(UserRoleDTO.QueryDTO userRoleQueryDTO) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, userRoleQueryDTO);

        BaseDeleted deleted = userRoleQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeleteList(queryWrapper);
        } else {
            return list(queryWrapper);
        }
    }

    private void queryWrapper(LambdaQueryWrapper<UserRole> queryWrapper, UserRoleDTO.QueryDTO userRoleQueryDTO) {

        Long userIdentityId = userRoleQueryDTO.getUserIdentityId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(userIdentityId), UserRole::getUserIdentityId, userIdentityId);

        Long roleId = userRoleQueryDTO.getRoleId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(roleId), UserRole::getRoleId, roleId);

        LocalDateTime expireTime = userRoleQueryDTO.getExpireTime();
        queryWrapper.eq(ObjectUtils.isNotEmpty(expireTime), UserRole::getExpireTime, expireTime);

        addQueryWrapper(queryWrapper, userRoleQueryDTO, getCommonColumn());

    }

    private Map<String, SFunction<UserRole, ?>> getCommonColumn() {
        return BaseEntity.getCommonColumn(
                UserRole::getOrderNumber,
                UserRole::getTenantId,
                UserRole::getApplicationId,
                UserRole::getStatus,
                UserRole::getDeleted,
                UserRole::getDeleteUserId,
                UserRole::getDeleteTime,
                UserRole::getRemark,
                UserRole::getCreateUserId,
                UserRole::getCreateTime,
                UserRole::getUpdateUserId,
                UserRole::getUpdateTime,
                UserRole::getExtend1,
                UserRole::getExtend2,
                UserRole::getExtend3);
    }

}
